import { _decorator, Component, Node, Prefab, NodeEventType, Tween, Vec3, UITransform, instantiate } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('game')
export class game extends Component {

    @property(Node)
    yuanPan:Node

    @property(Node)
    knifeNode:Node

    @property(Prefab)
    knifePrefab:Prefab
    //是否可以丢飞到
    canThrow : boolean = true
    knifeNodeArr = []

    onLoad(){
        this.yuanPan.setSiblingIndex(1)
        this.node.on(NodeEventType.TOUCH_START,this.throwKnife,this);
    }

    onDestory(){
        this.node.off(NodeEventType.TOUCH_START,this.throwKnife,this);
    }


    throwKnife() {
        if(this.canThrow){
            this.canThrow = false;
            let tween = new Tween(this.knifeNode);
            tween.to(0.25, { position: new Vec3(0,this.yuanPan.position.y-this.yuanPan.getComponent(UITransform).contentSize.width/2, 0) });
            tween.call(()=>{
                let isHit = false
                for( let knifeNode of this.knifeNodeArr){
                    if (Math.abs(this.knifeNode.angle-knifeNode.angle) < 10){
                        isHit = true;
                    }
                }
                if (isHit){
                    console.log("游戏结束");
                    let tween = new Tween(this.knifeNode);
                    tween.to(2, { position: new Vec3(0,-this.yuanPan.position.y, 0) });
                    tween.start();
                }else{
                    let knifeNode  = instantiate(this.knifePrefab);
                    knifeNode.setPosition(this.knifeNode.position)
                    this.node.addChild(knifeNode);
                    this.knifeNode.setPosition(new Vec3(0,-300,0))
                    this.canThrow = true
                    knifeNode.setSiblingIndex(0)
                    this.knifeNodeArr.push(knifeNode)
                }
            })
            tween.start();
        }
    }

    update(deltaTime: number) {
        this.yuanPan.angle = (this.yuanPan.angle + 1) % 360
        for( let knifeNode of this.knifeNodeArr){
            knifeNode.angle = (knifeNode.angle + 1) % 360 
            let r = this.yuanPan.getComponent(UITransform).contentSize.width/2
            let y = Math.sin(((knifeNode.angle-90)/180)*Math.PI - Math.PI/2)*r + this.yuanPan.position.y
            let x = Math.cos(((knifeNode.angle-90)/180)*Math.PI - Math.PI/2)*r
            knifeNode.setPosition(new Vec3(x,y,0))
        }


    }
}

